"""
性能监控模块
提供系统监控、内存优化和负载均衡功能
"""

from .performance_monitor import (
    Metric,
    MetricType,
    Alert,
    AlertLevel,
    AlertRule,
    MetricsCollector,
    SystemMonitor,
    AlertManager,
    PerformanceMonitor,
    performance_monitor
)
from .memory_optimizer import (
    MemorySnapshot,
    MemoryStatus,
    GCStrategy,
    GCMetrics,
    MemoryTracker,
    GCManager,
    MemoryOptimizer,
    memory_optimizer
)
from .load_balancer import (
    LoadBalancingStrategy,
    NodeStatus,
    NodeMetrics,
    ServiceNode,
    ScalingPolicy,
    ScalingDirection,
    HealthChecker,
    LoadBalancer,
    AutoScaler,
    LoadBalancingManager,
    load_balancing_manager
)

__all__ = [
    # 性能监控
    'Metric',
    'MetricType',
    'Alert',
    'AlertLevel',
    'AlertRule',
    'MetricsCollector',
    'SystemMonitor',
    'AlertManager',
    'PerformanceMonitor',
    'performance_monitor',
    
    # 内存优化
    'MemorySnapshot',
    'MemoryStatus',
    'GCStrategy',
    'GCMetrics',
    'MemoryTracker',
    'GCManager',
    'MemoryOptimizer',
    'memory_optimizer',
    
    # 负载均衡
    'LoadBalancingStrategy',
    'NodeStatus',
    'NodeMetrics',
    'ServiceNode',
    'ScalingPolicy',
    'ScalingDirection',
    'HealthChecker',
    'LoadBalancer',
    'AutoScaler',
    'LoadBalancingManager',
    'load_balancing_manager'
]

# 版本信息
__version__ = '1.0.0'
__author__ = 'Offline Language Player Team'


# 服务初始化
async def init_monitoring_services():
    """初始化监控服务"""
    try:
        # 启动性能监控
        await performance_monitor.start()
        
        # 启动内存优化器
        await memory_optimizer.start()
        
        logger = get_logger(__name__)
        logger.info("Monitoring services initialized successfully")
        return True
        
    except Exception as e:
        logger = get_logger(__name__)
        logger.error(f"Failed to initialize monitoring services: {e}")
        return False


# 服务清理
async def cleanup_monitoring_services():
    """清理监控服务"""
    try:
        # 停止性能监控
        await performance_monitor.stop()
        
        # 停止内存优化器
        await memory_optimizer.stop()
        
        logger = get_logger(__name__)
        logger.info("Monitoring services cleaned up successfully")
        return True
        
    except Exception as e:
        logger = get_logger(__name__)
        logger.error(f"Failed to cleanup monitoring services: {e}")
        return False


# 便捷函数
async def get_system_status() -> Dict[str, Any]:
    """获取系统状态（便捷函数）"""
    return {
        "performance": await performance_monitor.get_performance_summary(),
        "memory": memory_optimizer.get_optimization_report(),
        "load_balancing": await load_balancing_manager.get_global_stats()
    }


async def optimize_system(aggressive: bool = False) -> Dict[str, Any]:
    """优化系统（便捷函数）"""
    results = {}
    
    # 内存优化
    results["memory"] = memory_optimizer.optimize_now(aggressive=aggressive)
    
    # 可以添加其他优化逻辑
    
    return results


# 导入必要的模块
from ..core.logging import get_logger
from typing import Dict, Any
